<template>
  <div class="workorder-list">
    <!-- 搜索卡片 -->
    <a-card :bordered="false" class="search-card">
      <a-form layout="inline" :model="searchForm">
        <a-form-item label="工单编号">
          <a-input v-model:value="searchForm.workOrderId" placeholder="请输入工单编号" allowClear />
        </a-form-item>
        <a-form-item label="报修人账号">
          <a-input
            v-model:value="searchForm.reporterAccount"
            placeholder="请输入报修人账号"
            allowClear
          />
        </a-form-item>
        <a-form-item label="处理人账号">
          <a-input
            v-model:value="searchForm.handlerAccount"
            placeholder="请输入处理人账号"
            allowClear
          />
        </a-form-item>
        <a-form-item label="工单标题">
          <a-input v-model:value="searchForm.title" placeholder="请输入工单标题" allowClear />
        </a-form-item>
        <a-form-item label="报修地址">
          <a-input v-model:value="searchForm.location" placeholder="请输入报修地址" allowClear />
        </a-form-item>
        <a-form-item label="维修类别">
          <a-input
            v-model:value="searchForm.categoryName"
            placeholder="请输入类别名称"
            allowClear
          />
        </a-form-item>
        <a-form-item label="状态">
          <a-select
            v-model:value="searchForm.status"
            placeholder="请选择状态"
            style="width: 120px"
            allowClear
          >
            <a-select-option :value="WorkOrderStatus.PENDING">待处理</a-select-option>
            <a-select-option :value="WorkOrderStatus.IN_PROGRESS">处理中</a-select-option>
            <a-select-option :value="WorkOrderStatus.COMPLETED">已完成</a-select-option>
            <a-select-option :value="WorkOrderStatus.REVIEWED">已评价</a-select-option>
            <a-select-option :value="WorkOrderStatus.CANCELLED">已取消</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="创建时间">
          <a-range-picker
            v-model:value="dateRange"
            style="width: 240px"
            @change="handleDateRangeChange"
          />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" :icon="h(SearchOutlined)" @click="fetchData"> 搜索 </a-button>
            <a-button :icon="h(ReloadOutlined)" @click="resetSearch"> 重置 </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 数据表格 -->
    <a-card :bordered="false">
      <template #title>
        <span>工单列表</span>
        <a-tag color="blue" style="margin-left: 8px"> 共 {{ pagination.total }} 条 </a-tag>
      </template>

      <template #extra>
        <a-space>
          <a-button
            v-if="userStore.isStudent"
            type="primary"
            :icon="h(PlusOutlined)"
            @click="router.push('/workorder/create')"
          >
            创建工单
          </a-button>
          <a-button :icon="h(ReloadOutlined)" @click="fetchData"> 刷新 </a-button>
        </a-space>
      </template>

      <a-table
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :pagination="pagination"
        :locale="{ emptyText: '暂无数据' }"
        @change="handleTableChange"
        :scroll="{ x: 1200, y: 800 }"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </a-tag>
          </template>

          <template v-if="column.key === 'createdAt'">
            {{ formatDate(record.createdAt) }}
          </template>

          <template v-if="column.key === 'action'">
            <a-space>
              <a-button
                type="link"
                size="small"
                @click="router.push(`/workorder/detail/${record.id}`)"
              >
                查看
              </a-button>
              <a-button v-if="canEdit(record)" type="link" size="small" @click="handleEdit(record)">
                编辑
              </a-button>
              <a-button
                v-if="canCancel(record)"
                type="link"
                size="small"
                danger
                @click="handleCancel(record)"
              >
                取消
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { computed, h, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import { useUserStore } from '@/stores/user'
import { useAppStore } from '@/stores/app'
import { getWorkOrderList, updateWorkOrder } from '@/api/workorder'
import type { WorkOrder, WorkOrderQueryRequest, PageResponse, PaginationState } from '@/types'
import { WorkOrderStatus } from '@/types'
import { createPaginationFromResponse, handlePaginationNavigation } from '@/utils/pagination'
import { PlusOutlined, ReloadOutlined, SearchOutlined } from '@ant-design/icons-vue'

const router = useRouter()
const userStore = useUserStore()
const appStore = useAppStore()

const loading = ref(false)
const dataSource = ref<WorkOrder[]>([])

// 搜索表单
const searchForm = reactive<WorkOrderQueryRequest>({
  workOrderId: '',
  reporterAccount: '',
  handlerAccount: '',
  title: '',
  location: '',
  categoryName: '',
  status: undefined,
  createdAtStart: '',
  createdAtEnd: '',
  pageSize: 10,
  current: 1,
  lastId: 0,
})

// 日期范围
const dateRange = ref<[string, string] | null>(null)

// 分页状态管理
const paginationState = ref<PaginationState>({
  current: 1,
  pageSize: 10,
  total: 0,
  pages: 0,
  hasNext: false,
  nextCursor: 0,
  previousPageCursors: []
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number, range: [number, number]) =>
    `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
})

// 当前页面的起始lastId
const currentPageLastId = ref(0)

// 表格列配置
const columns = computed(() => {
  return [
    {
      title: '工单编号',
      dataIndex: 'workOrderId',
      key: 'workOrderId',
      width: 150,
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      width: 150,
    },
    {
      title: '维修类别',
      dataIndex: 'categoryName',
      key: 'categoryName',
      width: 120,
    },
    {
      title: '报修地址',
      dataIndex: 'location',
      key: 'location',
      width: 120,
    },
    {
      title: '报修人员',
      dataIndex: 'reporterAccount',
      key: 'reporterAccount',
      width: 120,
    },
    {
      title: '维修人员',
      dataIndex: 'handlerAccount',
      key: 'handlerAccount',
      width: 150,
      // 显示其他
      customRender: ({ text }: { text: string }) => {
        return text || '暂未分配'
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 120,
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      width: 200,
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      fixed: 'right' as const,
    },
  ]
})

// 获取状态颜色
const getStatusColor = (status: WorkOrderStatus) => {
  const colorMap = {
    [WorkOrderStatus.PENDING]: 'orange',
    [WorkOrderStatus.IN_PROGRESS]: 'blue',
    [WorkOrderStatus.COMPLETED]: 'green',
    [WorkOrderStatus.REVIEWED]: 'purple',
    [WorkOrderStatus.CANCELLED]: 'red',
  }
  return colorMap[status] || 'default'
}

// 获取状态文本
const getStatusText = (status: WorkOrderStatus) => {
  const textMap = {
    [WorkOrderStatus.PENDING]: '待处理',
    [WorkOrderStatus.IN_PROGRESS]: '处理中',
    [WorkOrderStatus.COMPLETED]: '已完成',
    [WorkOrderStatus.REVIEWED]: '已评价',
    [WorkOrderStatus.CANCELLED]: '已取消',
  }
  return textMap[status] || '未知'
}

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString()
}

// 判断是否可以编辑
const canEdit = (record: WorkOrder) => {
  // 只有报修人可以编辑自己的工单，且状态为待处理
  return (
    userStore.isStudent &&
    record.reporterId === userStore.userInfo?.id &&
    record.status === WorkOrderStatus.PENDING
  )
}

// 判断是否可以取消
const canCancel = (record: WorkOrder) => {
  // 只有报修人可以取消自己的工单，且状态为待处理或处理中
  return (
    userStore.isStudent &&
    record.reporterId === userStore.userInfo?.id &&
    (record.status === WorkOrderStatus.PENDING || record.status === WorkOrderStatus.IN_PROGRESS)
  )
}

// 获取工单列表
const fetchData = async (resetPagination = false, useLastId?: number) => {
  try {
    loading.value = true

    if (resetPagination) {
      // 重置分页状态
      paginationState.value = {
        current: 1,
        pageSize: searchForm.pageSize || 10,
        total: 0,
        pages: 0,
        hasNext: false,
        nextCursor: 0,
        previousPageCursors: []
      }
      currentPageLastId.value = 0
    }

    const queryParams = { ...searchForm }
    queryParams.pageSize = paginationState.value.pageSize
    queryParams.current = paginationState.value.current
    queryParams.lastId = useLastId !== undefined ? useLastId : currentPageLastId.value

    // 学生只能看自己的工单
    if (userStore.isStudent) {
      queryParams.reporterId = userStore.userInfo?.id
    }

    const response = await getWorkOrderList(queryParams)
    if (response.code === 0 && response.data) {
      const pageData = response.data as PageResponse<WorkOrder>

      // 更新数据源
      dataSource.value = pageData.records || []

      // 更新分页状态
      paginationState.value = {
        current: pageData.current,
        pageSize: pageData.size,
        total: pageData.total,
        pages: pageData.pages,
        hasNext: pageData.hasNext,
        nextCursor: pageData.nextCursor,
        previousPageCursors: paginationState.value.previousPageCursors
      }

      // 更新分页配置
      const paginationConfig = createPaginationFromResponse(pageData)
      Object.assign(pagination, paginationConfig)
    }
  } catch (error) {
    console.error('获取工单列表失败:', error)
    message.error('获取工单列表失败')
  } finally {
    loading.value = false
  }
}

// 日期范围变化处理
const handleDateRangeChange = (dates: [string, string] | null) => {
  if (dates) {
    searchForm.createdAtStart = dates[0]
    searchForm.createdAtEnd = dates[1]
  } else {
    searchForm.createdAtStart = ''
    searchForm.createdAtEnd = ''
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.workOrderId = ''
  searchForm.reporterAccount = ''
  searchForm.handlerAccount = ''
  searchForm.title = ''
  searchForm.location = ''
  searchForm.categoryName = ''
  searchForm.status = undefined
  searchForm.createdAtStart = ''
  searchForm.createdAtEnd = ''
  dateRange.value = null
  fetchData(true)
}

// 表格变化处理
const handleTableChange = (pag: any) => {
  const isNextPage = pag.current > paginationState.value.current
  const isPrevPage = pag.current < paginationState.value.current

  // 更新页面大小
  if (pag.pageSize !== paginationState.value.pageSize) {
    searchForm.pageSize = pag.pageSize
    paginationState.value.pageSize = pag.pageSize
    fetchData(true) // 页面大小变化时重置分页
    return
  }

  if (isNextPage && paginationState.value.hasNext) {
    // 向前翻页
    const navResult = handlePaginationNavigation(
      paginationState.value,
      'next',
      currentPageLastId.value
    )

    paginationState.value.current = navResult.current
    paginationState.value.previousPageCursors = navResult.previousCursors
    currentPageLastId.value = navResult.lastId

    fetchData(false, navResult.lastId)
  } else if (isPrevPage && paginationState.value.current > 1) {
    // 向后翻页
    const navResult = handlePaginationNavigation(
      paginationState.value,
      'prev',
      currentPageLastId.value
    )

    paginationState.value.current = navResult.current
    paginationState.value.previousPageCursors = navResult.previousCursors
    currentPageLastId.value = navResult.lastId

    fetchData(false, navResult.lastId)
  }
}

// 编辑工单
const handleEdit = (record: WorkOrder) => {
  router.push(`/workorder/edit/${record.id}`)
}

// 取消工单
const handleCancel = (record: WorkOrder) => {
  Modal.confirm({
    title: '确认取消',
    content: `确定要取消工单 "${record.workOrderId}" 吗？`,
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      try {
        const response = await updateWorkOrder({
          id: record.id,
          status: WorkOrderStatus.CANCELLED
        })
        if (response.code === 0) {
          message.success('工单已取消')
          await fetchData()
        } else {
          message.error(response.message || '操作失败')
        }
      } catch (error) {
        console.error('取消工单失败:', error)
        message.error('操作失败，请重试')
      }
    },
  })
}

onMounted(() => {
  // 设置面包屑
  appStore.setBreadcrumbs([
    { title: '首页', path: '/dashboard' },
    { title: '工单管理' },
    { title: '工单列表' },
  ])

  fetchData()
})
</script>

<style scoped>
.workorder-list {
  padding: 0;
}

.search-card {
  margin-bottom: 16px;
  padding-bottom: 20px;
}

.search-card :deep(.ant-card-body) {
  padding-bottom: 0;
}

.search-card .ant-form {
  gap: 16px;
}
</style>
